<template>
  <!--股权和融资信息-->
  <div>
    <div class="riskInfo">
      <div>
        <div class="courtTitle">
          <p class="infoTitle">目前参与计算公司的范围</p>
        </div>
        <div class="courtList">
          <el-table
            :data="listData"
            v-loading="dataListLoading"
            :header-cell-style="{ color: '#03b38c' }"
            max-height="280"
            style="width: 100%"
          >
            <el-table-column fixed prop="name" label="公司名称">
            </el-table-column>
            <el-table-column fixed width="120px" label="持股比例">
              <template slot-scope="scope">
                {{ scope.row.stockPercent | stockPercentFilter }}
              </template>
            </el-table-column>
            <el-table-column fixed width="120px" label="专利数量">
              <template slot-scope="scope">
                {{ scope.row.patentNum }}
              </template>
            </el-table-column>
            <el-table-column fixed prop="source" width="200px" label="数据来源">
              <template slot-scope="scope">
                {{ scope.row.source | sourceFilter2 }}
              </template>
            </el-table-column>
            <!--状态-->
            <el-table-column fixed width="150px" label="状态">
              <template slot-scope="scope">
                <span
                  v-if="scope.row.countType === false"
                  :style="scope.row.countType | status"
                  >待计算</span
                >
                <span v-else :style="scope.row.countType | status">已计算</span>
              </template>
            </el-table-column>
            <!-- v-if="scope.row.source===4" -->
            <el-table-column fixed="right" label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  v-if="scope.row.source !== 1"
                  :autofocus="false"
                  class="delete"
                  @click="DelectClick(scope.row)"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div v-if="pageChangeStatus" class="block">
            <!-- <vPagination
              :total="ListTotalNum"
              :ips="pageSize"
              :sendCurrentPage="currentPage"
              @currentPage="handleCurrentChange"
            /> -->
            <el-pagination
                background
                layout="prev, pager, next"
                :total="ListTotalNum"
                :page-size="pageSize"
                :current-page.sync="currentPage"
                @current-change="handleCurrentChange"
                class="el-pagination"
              >
              </el-pagination>
          </div>
        </div>
      </div>
      <div>
        <div class="courtTitle">
          <p class="infoTitle">未参与计算的公司</p>
        </div>
        <div class="courtList">
          <el-table
            v-loading="dataListLoading2"
            :data="NotPartlistData"
            :header-cell-style="{ color: '#03b38c' }"
            max-height="280"
            style="width: 100%"
          >
            <el-table-column fixed prop="name" label="公司名称">
            </el-table-column>
            <el-table-column fixed width="150px" label="持股比例">
              <template slot-scope="scope">
                {{ scope.row.stockPercent | stockPercentFilter }}
              </template>
            </el-table-column>
            <el-table-column fixed width="150px" label="专利数量">
              <template slot-scope="scope">
                {{ scope.row.patentNum }}
              </template>
            </el-table-column>
            <el-table-column fixed prop="source" width="200px" label="数据来源">
              <template slot-scope="scope">
                {{ scope.row.source | sourceFilter }}
              </template>
            </el-table-column>
            <!-- :disabled='scope.row.disabled' -->
            <el-table-column fixed="right" label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  @click="handleClick(scope.row)"
                  class="delete"
                  type="primary"
                  size="small"
                  >并表</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="block" style="margin-top:20px;">
        <el-pagination
          background
          layout="prev, pager, next"
          @current-change="HandPageChange"
          :current-page="ipi"
          :page-size="notIps"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 手动添加 -->
      <div>
        <div class="courtTitle">
          <p class="infoTitle">手动添加</p>
        </div>
        <div class="courtList add">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="0"
            class="demo-ruleForm"
          >
            <el-table
              :data="ruleForm.addList"
              max-height="150"
              :header-row-style="{ border: 'none' }"
              :header-cell-style="{ color: '#03b38c', border: 'none' }"
              :row-style="{ border: 'none' }"
              :cell-style="{ border: 'none' }"
              style="width: 100%;border:none;"
            >
              <el-table-column fixed="left" label="公司名称">
                <template slot-scope="scope">
                  <el-form-item
                    style="margin:0 !important;"
                    :prop="`addList.${scope.$index}.name`"
                    :rules="rules.name"
                  >
                    <el-input
                      v-model="scope.row.name"
                      class="edit-input"
                      size="small"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column fixed="left" label="持股比例">
                <template slot-scope="scope">
                  <el-form-item
                    style="margin:0 !important;"
                    :prop="`addList.${scope.$index}.stockPercent`"
                    :rules="rules.stockPercent"
                  >
                    <el-input
                      v-model="scope.row.stockPercent"
                      placeholder="请输入0-1，小数保留两位"
                      class="edit-input"
                      size="small"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="" width="100">
                <template slot-scope="scope">
                  <el-button
                  class="btnClass"
                    type="primary"
                    @click="AddButton(scope.row)"
                    size="small"
                    >添加</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </div>
      <!-- 操作 -->
      <div class="footerButton">
        <el-button type="primary" @click="close" plain>关闭</el-button>
        <el-button class="btn" type="primary" @click="CalculatedData()"
          >重新计算</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import $ from "jquery";
import { setTimeout } from "timers";
// import vPagination from "./common/vPagination";
let that;
export default {
  data() {
    return {
      rules: {
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        stockPercent: [
          {
            required: true,
            validator: this.valiNumberPass,
            message: "请选择活动区域",
            trigger: "blur",
          },
        ],
      },
      ruleForm: {
        addList: [
          {
            name: "",
            id: "",
            stockPercent: "",
            Proportion: "",
            source: "4",
          },
        ],
      },
      searchText: "",
      companyName: this.$cookie.get("companyName") || " ", //公司名称

      listData: [],
      listDataCopy: [],
      structureChart: null,
      structureOption: null,
      hasOther: false,
      activeName: "second",
      tips: [
        this.$t("assessment.Shareholder"),
        this.$t("assessment.ForeignInvestment"),
      ],
      financing: {
        title: this.$t("assessment.FinancingInfo"),
        body: [],
      },
      leftHasOther: false,
      rightHasOther: false,
      //树形结构参数
      elId: "",
      leftCount: 0,
      rightCount: 0,
      treeData: {},
      hasSomeThing: false,
      // 翻页
      pageChangeStatus: true,
      ListTotalNum: 0,
      currentPage: 1,
      pageSize: 5,
      // 未参与计算公司
      NotPartlistData: [],
      NotPartlistDataAll: [],
      dataListLoading: false,
      dataListLoading2: false,
      ipi: 1,
      notIps: 5,
      total: 0,
    };
  },
  // components: { vPagination },
  watch: {
    "$i18n.locale"() {
      this.financing = {
        title: this.$t("assessment.FinancingInfo"),
        body: [],
      };
    },
  },
  beforeCreate() {
    that = this;
  },
  mounted() {
    this.init();
    // this.SubAgency(); // 获取原始公司
    // this.RecommendedSubsidiaries(); // 推荐子机构
    // this.getPatentInfo();   // 跳转到股权结构
    this.$Bus.$on("toAnalysisBox", (data) => {
      setTimeout(() => {
        let scroll = document.getElementById("analysisBox").offsetTop;
      }, 0);
    });
  },
  filters: {
    status(status) {
      let color = "";
      if (status === false) {
        color = "color:red";
      } else {
        color = "color:#17B3A3";
      }
      return color;
    },
    sourceFilter2(val) {
      if (val !== "" && val !== null && val !== undefined) {
        if (val === 1) {
          return "工商信息";
        } else if (val === 3) {
          return "其它(手动添加)";
          // this.$t("assessment.Others")
        } else if (val === 4) {
          return "手动添加";
          // this.$t('assessment.ManualAddition')
        } else if (val === 5) {
          return "近似名称(手动添加)";
        } else if (val === 6) {
          return "子机构英文名称(手动添加)";
        } else if (val === 7) {
          return "疑似子机构(手动添加)";
        } else if (val === 8) {
          return "工商信息(非控股)";
        } else {
          return "-";
        }
      } else {
        return "-";
      }
    },
    sourceFilter(val) {
      if (val !== "" && val !== null && val !== undefined) {
        if (val === 1) {
          return "工商信息";
        } else if (val === 3) {
          return "其它";
          // this.$t("assessment.Others")
        } else if (val === 4) {
          return "手动添加";
          // this.$t('assessment.ManualAddition')
        } else if (val === 5) {
          return "近似名称";
        } else if (val === 6) {
          return "子机构英文名称";
        } else if (val === 7) {
          return "疑似子机构";
        } else if (val === 8) {
          return "工商信息(非控股)";
        } else {
          return "-";
        }
      } else {
        return "-";
      }
    },
    stockPercentFilter(val) {
      if (val === "" || val === 0 || val === null || val === undefined) {
        return "-";
      } else {
        return val;
      }
    },
  },
  methods: {
    ref() {
      this.SubAgency(); // 获取原始公司
      this.RecommendedSubsidiaries(); // 推荐子机构
    },
    // 持股比例正则
    valiNumberPass(rule, value, callback) {
      var re = /^(1|0(\.\d{1,2})?)$/;
      if (value === "") {
        callback(new Error("请输入内容"));
      } else if (!re.test(value)) {
        callback(new Error("请输入0-1,保留两位小数"));
      } else {
        callback();
      }
    },
    // 关闭回调
    close() {
      this.$emit("dialogCompanyListFalse");
    },
    // 每页多少条数
    handleSizeChange(val) {
      if (val !== null && val !== undefined && val !== "") {
        this.pageSize = val;
        this.$nextTick(() => {
          this.pageChangeStatus = false;
          this.pageChangeStatus = true;
        });
        this.SubAgency();
      }
    },
    // 翻页
    handleCurrentChange(val) {
      if (val !== null && val !== undefined && val !== "") {
        this.currentPage = val;
        this.$nextTick(() => {
          this.pageChangeStatus = false;
          this.pageChangeStatus = true;
        });
        this.SubAgency();
        // this.listData = this.listDataCopy.slice((this.currentPage-1)*this.pageSize,this.currentPage*this.pageSize)
      }
    },
    // 合并
    handleClick(row) {
      this.AddButton(row, "merge");
    },
    //删除
    DelectClick(val) {
      /* 
          return */
      this.$confirm("删除后将影响该公司专利统计结果，确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$delete(`api/companyes/subOrg/delete/${val.id}`, {})
            .then((res) => {
              if (res) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                // let n=false
                /* for(let i=0;i<this.NotPartlistData.length;i++){
                      if(val.name ===this.NotPartlistData[i].name){
                        // n = true
                        
                      }
                    } */
                /* if(n ===false){
                      this.NotPartlistData.unshift(val)
                    } */
              }
              // 不是手动添加的
              if (val.source != "4") {
                this.RecommendedSubsidiaries("delete");
              }
              this.SubAgency();
            })
            .catch((e) => {
              console.log(e);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消删除",
          });
        });
    },
    // 推荐机构翻页
    HandPageChange(val) {
      this.ipi = val;
      this.NotPartlistData = this.NotPartlistDataAll.slice(
        (this.ipi - 1) * 5,
        this.ipi * 5
      );
    },
    // 推荐机构
    RecommendedSubsidiaries(val) {
      this.dataListLoading2 = true;
      let url = `api/companyes/subOrg/sim/${this.companyName}`;
      this.$get(url, {})
        .then((res) => {
          // console.log(res.data)
          this.dataListLoading2 = false;
          if (res.data) {
            this.NotPartlistDataAll = JSON.parse(JSON.stringify(res.data));
            this.total = res.data.length;
            this.NotPartlistData = this.NotPartlistDataAll.slice(
              (this.ipi - 1) * 5,
              this.ipi * 5
            );
            // 如果是删除初始化页码
            if (val) this.ipi = 1;

            /* for(let i=0;i<this.listData.length;i++){
                for(let j =0;j<this.NotPartlistData.length;j++){
                  if(this.listData[i].name ===this.NotPartlistData[j].name){
                    this.$set(this.NotPartlistData[j],'disabled',true)
                  }
                }
              } */
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    // 默认计算公司
    SubAgency() {
      this.dataListLoading = true;
      let sq = `api/companyes/subOrg/page/${this.currentPage}/${this.pageSize}/${this.companyName}`;
      // let sq = `api/companyes/subOrg/page/${this.companyName}`
      this.$get(sq, {})
        .then((res) => {
          // console.log(res)
          this.dataListLoading = false;
          if (res) {
            /* this.listDataCopy = res.data
              this.listData = this.listDataCopy.slice((this.currentPage-1)*this.pageSize,this.currentPage*this.pageSize) */
            this.listData = res.data.result;
            this.$nextTick(() => {
              this.pageChangeStatus = false;
              this.pageChangeStatus = true;
            });
            this.ListTotalNum = res.data.total;
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    // 重新计算
    CalculatedData() {
      this.$confirm("是否重新计算数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$get(this.$Url.compaines.CalculatedData, {
            companyName: this.companyName,
          })
            .then((res) => {
              if (res) {
                this.$router.push({
                  name: "searchList",
                  query: {
                    companyName: this.companyName,
                  },
                });
                // console.log(res)
              }
            })
            .catch((e) => {
              console.log(e);
            });
          /*this.$message({
          type: 'success',
          message: '正在重新计算数据!'
        });*/
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重新计算",
          });
        });
    },
    // 手动添加子机构到当前公司
    AddButton(searchText, merge) {
      /* console.log(searchText)
         return  */
      let source = searchText.source || "";
      // 判断是否合并还是手动添加
      if (merge !== "merge") {
        // 手动
        this.$refs["ruleForm"].validate((valid) => {
          if (valid) {
            add(source, "iden");
          } else {
            this.$message.warning("请输入正确内容！");
            return false;
          }
        });
      } else {
        // 合并
        for (let i = 0; i < this.NotPartlistData.length; i++) {
          if (this.NotPartlistData[i].name === searchText.name) {
            // console.log(i)
            this.$set(this.NotPartlistData[i], "disabled", true);
          }
        }
        // return
        add(source);
      }
      // function VirtualAdd(){}
      function add(source, iden) {
        let data = {
          subName: searchText.name,
          stockPercent: Number(searchText.stockPercent),
          parentName: that.companyName,
          source: source,
        };
        that
          .$post(that.$Url.compaines.addSubOrg, data)
          .then((res) => {
            if (res) {
              // console.log(res)
              // 清空添加信息
              that.ruleForm.addList = [
                {
                  name: "",
                  id: "",
                  Proportion: "",
                  stockPercent: "",
                  source: "4",
                },
              ];
              that.$message({
                type: "success",
                message: "添加成功!",
              });
              // 如果是并表，手动删除为计算公司当前这条
              if (!iden) {
                that.RecommendedSubsidiaries();
              }
              // 刷新计算公司的接口
              that.SubAgency();
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },

    // function: 初始化
    init() {
      let time = new Date().getTime();
      this.elId = "tree_" + time;
    },
    //* function: 绘制树
    drawTree() {
      var ths = this;
      // Calculate total nodes, max label length
      //计算总节点，最大标签长度
      var totalNodes = 0;
      var maxLabelLength = 0;
      // variables for drag/drop
      var selectedNode = null;
      var draggingNode = null;
      // panning variables
      var panSpeed = 200;
      var panBoundary = 20; // Within 20px from edges will pan when dragging.
      // Misc. variables
      var i = 0;
      var duration = 750;
      var root;
      var dragStarted = null;
      var domNode = null;
      var nodes = [];

      // size of the diagram
      var viewerWidth = $("#" + ths.elId).width();
      var viewerHeight = $("#" + ths.elId).height();
      var tree = d3.layout.tree().size([viewerHeight, viewerWidth]);
      // define a d3 diagonal projection for use by the node paths later on.
      //定义一个D3对角线投影，供以后节点路径使用
      var diagonal = d3.svg.diagonal().projection(function(d) {
        return [d.y, d.x];
      });
      // A recursive helper function for performing some setup by walking through all nodes
      //通过遍历所有节点执行一些设置的递归辅助函数
      function visit(parent, visitFn, childrenFn) {
        if (!parent) return;

        visitFn(parent);

        var children = childrenFn(parent);
        if (children) {
          var count = children.length;
          for (var i = 0; i < count; i++) {
            visit(children[i], visitFn, childrenFn);
          }
        }
      }
      // Call visit function to establish maxLabelLength
      //建立最大长度的函数
      visit(
        this.treeData,
        function(d) {
          //		      	console.log(this.treeData);
          totalNodes++;
          maxLabelLength = Math.max(d.name.length, maxLabelLength);
        },
        function(d) {
          return d.children && d.children.length > 0 ? d.children : null;
        }
      );
      // sort the tree according to the node names
      //根据节点名称排序树
      function sortTree() {
        tree.sort(function(a, b) {
          return b.name.toLowerCase() < a.name.toLowerCase() ? 1 : -1;
        });
      }
      // Sort the tree initially incase the JSON isn't in a sorted order.
      //如果JSON不按排序顺序，则首先对树进行排序。
      //sortTree();

      // Define the zoom function for the zoomable tree
      //定义可缩放树的缩放函数
      function zoom() {
        svgGroup.attr(
          "transform",
          "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"
        );
      }

      // define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents
      //定义zoomListener，它调用在缩放范围内的“缩放”事件上的缩放功能
      var zoomListener = d3.behavior
        .zoom()
        .scaleExtent([0.5, 3])
        .on("zoom", zoom);

      function initiateDrag(d, domNode) {
        draggingNode = d;
        d3.select(domNode)
          .select(".ghostCircle")
          .attr("pointer-events", "none");
        d3.selectAll(".ghostCircle").attr("class", "ghostCircle show");
        d3.select(domNode).attr("class", "node activeDrag");

        svgGroup.selectAll("g.node").sort(function(a, b) {
          // select the parent and sort the path's
          if (a.id != draggingNode.id) return 1;
          // a is not the hovered element, send "a" to the back
          else return -1; // a is the hovered element, bring "a" to the front
        });
        // if nodes has children, remove the links and nodes
        if (nodes.length > 1) {
          // remove link paths
          var links = tree.links(nodes);
          var nodePaths = svgGroup
            .selectAll("path.link")
            .data(links, function(d) {
              return d.target.id;
            })
            .remove();
          // remove child nodes
          var nodesExit = svgGroup
            .selectAll("g.node")
            .data(nodes, function(d) {
              return d.id;
            })
            .filter(function(d, i) {
              if (d.id == draggingNode.id) {
                return false;
              }
              return true;
            })
            .remove();
        }
        // remove parent link
        var parentLink = tree.links(tree.nodes(draggingNode.parent));
        svgGroup
          .selectAll("path.link")
          .filter(function(d, i) {
            //		        	console.log(d)
            if (d.target.id == draggingNode.id) {
              return true;
            }
            return false;
          })
          .remove();

        dragStarted = null;
      }

      // define the baseSvg, attaching a class for styling and the zoomListener
      var baseSvg = d3
        .select("#" + ths.elId)
        .append("svg")
        .attr("width", viewerWidth)
        .attr("height", viewerHeight)
        .attr("class", "overlay")
        .call(zoomListener);
      function endDrag() {
        selectedNode = null;
        d3.selectAll(".ghostCircle").attr("class", "ghostCircle");
        d3.select(domNode).attr("class", "node");
        // now restore the mouseover event or we won't be able to drag a 2nd time
        d3.select(domNode)
          .select(".ghostCircle")
          .attr("pointer-events", "");
        updateTempConnector();
        if (draggingNode !== null) {
          update(root);
          centerNode(draggingNode);
          draggingNode = null;
        }
      }

      // Helper functions for collapsing and expanding nodes.
      function collapse(d) {
        if (d.children) {
          d._children = d.children;
          d._children.forEach(collapse);
          d.children = null;
        }
      }

      function expand(d) {
        if (d._children) {
          d.children = d._children;
          d.children.forEach(expand);
          d._children = null;
        }
      }

      var overCircle = function(d) {
        selectedNode = d;
        updateTempConnector();
      };
      var outCircle = function(d) {
        selectedNode = null;
        updateTempConnector();
      };

      // Function to update the temporary connector indicating dragging affiliation
      var updateTempConnector = function() {
        var data = [];
        if (draggingNode !== null && selectedNode !== null) {
          // have to flip the source coordinates since we did this for the existing connectors on the original tree
          data = [
            {
              source: {
                x: selectedNode.y0,
                y: selectedNode.x0,
              },
              target: {
                x: draggingNode.y0,
                y: draggingNode.x0,
              },
            },
          ];
        }
        var link = svgGroup.selectAll(".templink").data(data);

        link
          .enter()
          .append("path")
          .attr("class", "templink")
          .attr("d", d3.svg.diagonal())
          .attr("pointer-events", "none");

        link.attr("d", d3.svg.diagonal());

        link.exit().remove();
      };

      // Function to center node when clicked/dropped so node doesn't get lost when collapsing/moving with large amount of children.

      function centerNode(source) {
        var scale = zoomListener.scale();
        var x = -source.y0;
        var y = -source.x0;
        x = x * scale + viewerWidth / 2;
        y = y * scale + viewerHeight / 2;

        d3.select("#" + ths.elId)
          .select("g")
          .transition()
          .duration(duration)
          .attr(
            "transform",
            "translate(" + x + "," + y + ")scale(" + scale + ")"
          );
        zoomListener.scale(scale);
        zoomListener.translate([x, y]);
      }

      // Toggle children function
      // function toggleChildren(d) {
      //   if (d.children) {
      //     d._children = d.children;
      //     d.children = null;
      //   } else if (d._children) {
      //     d.children = d._children;
      //     d._children = null;
      //   }
      //   return d;
      // }

      function update(source) {
        // Compute the new height, function counts total children of root node and sets tree height accordingly.
        // This prevents the layout looking squashed when new nodes are made visible or looking sparse when nodes are removed
        // This makes the layout more consistent.
        var levelWidth = [1];
        var childCount = function(level, n) {
          if (n.children && n.children.length > 0) {
            if (levelWidth.length <= level + 1) levelWidth.push(0);
            levelWidth[level + 1] += n.children.length;
            n.children.forEach(function(d) {
              childCount(level + 1, d);
            });
          }
        };
        childCount(0, root);
        var newHeight = d3.max(levelWidth) * 30; // 25 pixels per line每个的上下距离
        tree = tree.size([newHeight, viewerWidth]);

        // Compute the new tree layout.
        var nodes = tree.nodes(root).reverse(),
          links = tree.links(nodes);

        // Set widths between levels based on maxLabelLength.
        //区分左右
        nodes.forEach(function(d) {
          //如果是cite放在右边
          //ref右   cite左
          if (d.type === "cite") {
            //左
            d.y = -d.depth * (maxLabelLength * 6); //maxLabelLength * 10px局中心的距离
            d.x = d.x + 12.5 * ths.rightCount; //两边居中
          } else if (d.type === "ref") {
            //右
            d.y = d.depth * (maxLabelLength * 6); //maxLabelLength * 10px
            d.x = d.x - 12.5 * ths.leftCount; //两边居中
          } else {
            d.y = d.depth * (maxLabelLength * 6); //maxLabelLength * 10px
          }
          // alternatively to keep a fixed scale one can set a fixed depth per level
          // Normalize for fixed-depth by commenting out below line
          // d.y = (d.depth * 500); //500px per level.
        });

        // Update the nodes…
        var node = svgGroup.selectAll("g.node").data(nodes, function(d) {
          return d.id || (d.id = ++i);
        });

        // Enter any new nodes at the parent's previous position.
        var nodeEnter = node
          .enter()
          .append("g")
          .attr("class", "node")
          .attr("transform", function(d) {
            return "translate(" + source.y0 + "," + source.x0 + ")";
          });

        nodeEnter
          .append("circle")
          .attr("class", "nodeCircle")
          .attr("r", 0)
          .style("fill", function(d) {
            return d._children ? "lightsteelblue" : "#fff";
          });

        nodeEnter
          .append("text")
          .attr("x", function(d) {
            //如果是cite放在左边
            if (d.type === "cite") {
              return d.children || d._children ? 10 : -10;
            } else if (d.type === "ref") {
              return d.children || d._children ? -10 : 10;
            } else {
              return d.children || d._children ? 0 : 10;
            }
          })
          .attr("dy", ".35em")
          // .attr('class', 'nodeText')
          .attr("class", function(d) {
            if (d.type === "cite") return "nodeTextLeft";
            else if (d.type === "ref") return "nodeTextRight";
            else return "nodeTextModdle";
          })
          .attr("text-anchor", function(d) {
            //如果是cite放在左边
            if (d.type === "cite") {
              return d.children || d._children ? "start" : "end";
            } else if (d.type === "ref") {
              return d.children || d._children ? "end" : "start";
            } else {
              return d.children || d._children ? "center" : "start";
            }
          })
          .text(function(d) {
            return d.name;
          })
          .style("fill-opacity", 0);

        // phantom node to give us mouseover in a radius around it
        nodeEnter
          .append("circle")
          // .attr('class', 'ghostCircle')
          .attr("class", function(d) {
            if (d.type === "cite") return "circleLeft";
            else if (d.type === "ref") return "circleRight";
          })
          // .attr("r", 30)
          .attr("r", 6) //节点大小
          .attr("opacity", 0.8) // change this to zero to hide the target area
          // .style("fill", "$mainColor")//节点颜色
          .attr("pointer-events", "mouseover")
          .on("mouseover", function(node) {
            overCircle(node);
          })
          .on("mouseout", function(node) {
            outCircle(node);
          });

        // Update the text to reflect whether node has children or not.
        node
          .select("text")
          .attr("x", function(d) {
            //如果是cite放在左边
            if (d.type === "cite") {
              return d.children ? 10 : -10;
            } else if (d.type === "ref") {
              return d.children ? -10 : 10;
            } else {
              return d.children ? -30 : 10;
            }
          })
          .attr("y", function(d) {
            //如果是cite放在左边
            if (d.type === "cite" || d.type === "ref") {
              return 0;
            } else {
              return -20;
            }
          })
          .attr("text-anchor", function(d) {
            //如果是cite放在左边
            if (d.type === "cite") {
              return d.children ? "start" : "end";
            } else if (d.type === "ref") {
              return d.children ? "end" : "start";
            } else {
              return d.children ? "center" : "start";
            }
          })
          .text(function(d) {
            return d.name;
          });

        // Change the circle fill depending on whether it has children and is collapsed
        node
          .select("circle.nodeCircle")
          .attr("r", 4.5)
          .style("fill", function(d) {
            return "#fff";
          });

        // Transition nodes to their new position.
        var nodeUpdate = node
          .transition()
          .duration(duration)
          .attr("transform", function(d) {
            return "translate(" + d.y + "," + d.x + ")";
          });

        // Fade the text in
        nodeUpdate.select("text").style("fill-opacity", 1);

        // Transition exiting nodes to the parent's new position.
        var nodeExit = node
          .exit()
          .transition()
          .duration(duration)
          .attr("transform", function(d) {
            return "translate(" + source.y + "," + source.x + ")";
          })
          .remove();

        nodeExit.select("circle").attr("r", 0);

        nodeExit.select("text").style("fill-opacity", 0);
        //树的圆点的点击事件
        function click(d) {
          let index = d.name.indexOf("( 持股");
          if (index > -1) {
            ths.companyName = d.name.substr(0, index);
          } else {
            ths.companyName = d.name;
          }
          if (d.qtype === "E") {
            // 重绘
            baseSvg.remove();
            ths.getAData();
          } else {
            ths.$message.warning("非工商注册的企业");
          }
        }
        var OCircle = svgGroup.selectAll("circle").on("click", click);

        //文本点击事件
        // svgGroup.selectAll("text")
        //   .on("click", function (d) {
        //     ths.goDetail(d.name);
        //   });

        // Update the links…
        var link = svgGroup.selectAll("path.link").data(links, function(d) {
          return d.target.id;
        });
        // Enter any new links at the parent's previous position.
        link
          .enter()
          .insert("path", "g")
          .attr("class", "link")
          .attr("d", function(d) {
            var o = {
              x: source.x0,
              y: source.y0,
            };
            return diagonal({
              source: o,
              target: o,
            });
          });

        // Transition links to their new position.
        link
          .transition()
          .duration(duration)
          .attr("d", diagonal);

        // Transition exiting nodes to the parent's new position.
        link
          .exit()
          .transition()
          .duration(duration)
          .attr("d", function(d) {
            var o = {
              x: source.x,
              y: source.y,
            };
            return diagonal({
              source: o,
              target: o,
            });
          })
          .remove();

        // Stash the old positions for transition.
        nodes.forEach(function(d) {
          d.x0 = d.x;
          d.y0 = d.y;
        });
      }

      // Append a group which holds all nodes and which the zoom Listener can act upon.
      var svgGroup = baseSvg.append("g");
      // Define the root
      root = this.treeData;
      root.x0 = viewerHeight / 2;
      root.y0 = 0;

      // Layout the tree initially and center on the root node.
      update(root);
      centerNode(root);
    },
    /*
     * params: 无
     * return: 无
     * function: 获取PN号
     * */
    /*getPatentInfo() {
      this.getAData();
    },*/
  },
};
</script>

<style lang="scss" scoped>
.btnClass{
  background-color: $mainColor !important;
}

.block {
  text-align: center;
}
.delete:focus {
  background: $mainColor;
}
.classify {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  width: 100px;
  height: 40px;
  line-height: 40px;
  border: 1px solid #e7e7fc;
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
  text-align: center;
  font-size: 14px;
  color: #7674a3;
  background-color: #f5f6fc;
  cursor: text;
}
.search-bar {
  display: block;
  padding-left: 100px;
  padding-right: 150px;
}
.search-btn {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 2;
  width: 150px;
  height: 40px;
  border: 1px solid #e7e7fc;
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
  /* box-sizing: border-box; */
  text-align: center;
  font-size: 14px;
  color: #7775da;
  background-color: #e7e7fc;
  cursor: pointer;
}
.company {
  font-size: 12px;
  cursor: pointer;
}
.company:nth-of-type(1) {
  margin-top: 16px;
}
.company:hover {
  text-decoration: underline;
  color: $mainColor;
}

.company-list {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}
.link {
  fill: none !important;
  stroke: gray;
  stroke-width: 1.5px;
}
#d3Frame {
  padding-left: 10px;
}
/*g{transform: translate(120, 5);}
	:not(svg) { transform-origin: 0px 0px; }*/

.infoTitle {
  padding-left: 25px;
  margin: 12px 0;
  font-size: 18px;
  color: $mainColor;
  font-weight: bold;
  border-left: 5px solid $mainColor;
}
/*融资信息*/
.financing,
.structure {
  padding: 1px 0;
  background-color: #fff;
}
.branchBody,
.structureChart {
  width: 100%;
  padding: 0 50px;
}

/*股权结构*/
.structure {
  margin-top: 10px;
}
.structureChart {
  height: 500px;
}
.structure > .infoTitle {
  margin-bottom: 10px;
}
.analysisBox {
  position: relative;
}
.nothing {
  display: none;
  text-align: center;
  font-size: 15px;
  color: #666;
}
.nothing.show {
  display: block;
  position: relative;
  width: 100%;
  left: 0;
}

.tips,
.tips > p {
  display: flex;
  flex-wrap: nowrap;
}
.tips {
  padding: 0 30px;
  margin-bottom: 5px;
  color: #333;
  font-weight: bold;
}
.tips > p {
  margin-right: 25px;
  align-items: center;
}
.tips > p > b {
  width: 10px;
  height: 10px;
  margin-right: 6px;
  border-radius: 10px;
  background: $mainColor;
}
.tips > p:last-of-type > b {
  background: #b4c4ff;
}
.search-history {
  display: flex;
  flex-wrap: wrap;
  padding-left: 10px;
  margin-top: 14px;
  margin-bottom: 10px;
  list-style: none;
}
.search-history li {
  padding: 4px 16px;
  margin-right: 14px;
  margin-bottom: 10px;
  border-radius: 14px;
  font-size: 12px;
  color: #7775da;
  background-color: #e7e7fc;
  cursor: pointer;
}
.search-history li:hover {
  color: #fff !important;
  background-color: $mainColor !important;
}
.search-history .active {
  font-weight: 600;
  color: #fff !important;
  background-color: $mainColor !important;
}
.header {
  line-height: 40px;
  font-weight: bold;
  font-size: 16px;
}
.footerButton {
  position: relative;
  padding: 15px 0;
  text-align: center;
  margin-top: -1px;
  background: #fff;
  z-index: 100;
}
.courtTitle {
  display: flex;
  flex-wrap: nowrap;
  justify-content: space-between;
  margin: 10px 0 0 0;
}
.btn {
  background: $mainColor;
  border: 1px solid $mainColor;
}
.btn:hover {
  background: $mainColor;
  border: 1px solid $mainColor;
}
</style>
